import axios from "axios"
import store from '@/store'
import { getToken } from '@/utils/cookie'
import { message as Message } from 'ant-design-vue'


// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 200000, // request timeout
  retry: 3 //request retry times
})

const codeMessage = {
  0: '服务器连接超时, REQUEST TIMEOUT',
  8: '您的登录状态已失效，请重新登录！',
  200: 'SUCCESS',
  201: 'ADD OR UPDATE FINISHED',
  202: 'THE REQUEST SUCCESS INTO THE TASK（ASYNC METHODS)',
  204: 'DELETE OK',
  400: '请求异常，服务器没有进行相应新建或修改数据的操作。',
  401: '权限验证失败（令牌/用户名/密码错误）。',
  403: '您无法（无权限）访问当前资源！',
  404: '当前请求已失效或未发布上线，请联系系统管理员',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误!',
  500: '当前服务不可用，发生了未知异常，请稍后尝试 !',
  502: '网关发生异常，请稍后尝试 ！',
  503: '当前服务不可用，过载或维护中，请稍后尝试 ！',
  504: '连接超时，请稍后尝试或联系系统管理员.',
  5001: '当前服务不可用，发生了未知异常，请稍后尝试 !'
}

const exceptionCodes = [40001, 5000, 5001, 5500, 5501, 5502, 5503, 5504, 5505, 5506, 50000, 50001, 500012]

const tokenCodes = [4000, 4001, 4002, 4003]

//request interceptor
service.interceptors.request.use(
  config => {
    //before your request

    if (store.getters.token) {
      // let each request carry token
      config.headers['interactive-key'] = getToken()
      // config.headers['loginToken'] = getUpmadeToken()
      // config.headers['loginToken'] = 'system-20210407170208-VQCt9z1O'
    }
    return config;
  },
  error => {
    //catch the request error
    //console.log(error) // for debug
    return Promise.reject(error);
  })



// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * You can also judge the status by HTTP Status Code
   */
  response => {

    const res = response.data

    if (typeof res == Object) res._headers = response.headers

    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 20000 || res.code !== 2000) {

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50014 || tokenCodes.find(code => code == res.code)) {
        // to re-login
        Message.warning(codeMessage[8], 7 * 1)
        setTimeout(function () {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        }, 1500)
        return Promise.reject(new Error(res.message || codeMessage[8]))
      }

      // Upmade Service Error 5000-5999,  SOA Service Error 50000 - 59999
      if (exceptionCodes.find(code => code === res.code)) {

        Message.error(res.message || codeMessage[res.code] , 7 * 1)

        return Promise.reject(new Error(res.message || codeMessage[res.code]))
      }

      if (response.status == 200) return res // pass all response.status == 200 as default

      return Promise.reject(new Error(res.message || 'No Type Error ...'))

    } else {

      return res

    }

  },
  error => {

    const response = error.response || error.request

    let message = (response.data ? response.data.message : false) || codeMessage[response.status]

    switch (response.status) {
      case 400 || 401 || 403: //token expired
        Message.warning(codeMessage[response.status], 7 * 1)
        setTimeout(function () {
            store.dispatch('user/resetToken').then(() => {
              location.reload()
            })
        }, 1500)
        return Promise.reject(new Error(codeMessage[response.status]))

      case 0:
        return Promise.reject(new Error(codeMessage[response.status]))

      case 500:
        if (response.data.code == 'SESSION_AUTH_ERROR' || response.data.code == 'INVALID_INTERACTIVE_KEY') {

          Message.warning(codeMessage[8], 7 * 1)

          setTimeout(function () {
            store.dispatch('user/resetToken').then(() => {
              location.reload()
            })
          }, 1500)

          return Promise.reject(new Error(codeMessage[8]))
        }
    }

    Message.error(message, 7 * 1)

    return Promise.reject(new Error(message))

  })


export default service
